package com.chis.gencode;

import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.SecureRandom;

public class AesTest {

    public static void main(String[] args) {
        try {



            String content = "f190e80b176947ac9dc9466029c7b669";
            String auth = "27e11a04ea0f43609b20dcc3e8ba2204";

            byte[] en = encrypt(content.getBytes(),auth);
            System.out.println("加密："+new String(en));

//            byte[] de = decrypt(en,auth);
//            System.out.println("解码："+new String(de));

        } catch (Exception e){
            e.printStackTrace();
        }


    }

    public static byte[] test(byte[] content, String password) throws Exception {
        try {
            KeyGenerator kgen = KeyGenerator.getInstance("AES");
            SecureRandom secureRadmon= SecureRandom.getInstance("SHA1PRNG");
            secureRadmon.setSeed(password.getBytes());
            kgen.init(128,secureRadmon);

            SecretKey secretKey =kgen.generateKey();
            byte[] enCodeFormat = secretKey.getEncoded();
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");//"算法/模式/补码方式"
            cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(enCodeFormat, "AES"));// 初始化为加密模式的密码器
            return cipher.doFinal(content);// 加密
        } catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    public static byte[] encrypt(byte[] content, String password) {
        try {
            KeyGenerator kgen = KeyGenerator.getInstance("AES");// 创建AES的Key生产者
            kgen.init(128, new SecureRandom(password.getBytes()));// 利用用户密码作为随机数初始化出
            byte[] enCodeFormat = kgen.generateKey().getEncoded();// 返回基本编码格式的密钥，如果此密钥不支持编码，则返回
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");//"算法/模式/补码方式"
            cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(enCodeFormat, "AES"));// 初始化为加密模式的密码器
            return cipher.doFinal(content);// 加密
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static byte[] decrypt(byte[] content, String password) {
        try {
            KeyGenerator kgen = KeyGenerator.getInstance("AES");// 创建AES的Key生产者
            kgen.init(128, new SecureRandom(password.getBytes()));
            byte[] enCodeFormat = kgen.generateKey().getEncoded();// 返回基本编码格式的密钥
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");// 创建密码器
            cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(enCodeFormat, "AES"));// 初始化为解密模式的密码器
            byte[] result = cipher.doFinal(content);
            return result; // 明文
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
